import router from './router'
import store from './store'
import getPageTitle from '@/utils/get-page-title'

import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'
import {getToken} from "@/utils/auth"; // progress bar style

NProgress.configure({showSpinner: false}) // NProgress Configuration
// 每次fromA页面toB页面都向服务器请求用户信息并赋值给vuex中state
//必须调用next否则跳转失败
router.beforeEach(async (to, from, next) => {//在每次页面跳转前做的事情
    
    NProgress.start()// 页面跳转进度条开始
    document.title = getPageTitle(to.meta.title)//设置每个页面标题
    const hasToken = getToken();// 从js-cookie中尝试获取token

    if (hasToken) {
        if (to.path === '/login') {
            next({path: '/'})// 已登录，就跳转首页
            NProgress.done()//进度条停止
        } else {//有token要去别的页面就要获取用户信息并赋值给vuex中state
            await store.dispatch('user/getInfo')
            next()//放行
        }
    } else {
        next()
    }
})

router.afterEach(() => {
    // 跳转结束完成进度条
    NProgress.done()
})